<template>
	<view class="course-detail-container">
		<!-- 顶部导航 -->
		<view class="nav-bar">
			<view class="nav-left" @click="goBack">
				<text class="iconfont icon-fanhui"></text>
			</view>
			<view class="nav-title">{{courseInfo.title || '课程详情'}}</view>
			<view class="nav-right">
				<text class="iconfont icon-xiazai"></text>
				<text class="iconfont icon-fenxiang ml-20"></text>
			</view>
		</view>
		
		<!-- 主图区域 -->
		<view class="banner-image" v-if="!courseInfo.sliderImage || courseInfo.sliderImage.length <= 1">
			<image :src="courseInfo.banner || '/static/images/course_banner.jpg'" mode="aspectFill"></image>
		</view>
		
		<!-- 轮播图区域 -->
		<swiper v-else class="banner-swiper" indicator-dots autoplay circular interval="3000" duration="500">
			<swiper-item v-for="(item, index) in courseInfo.sliderImage" :key="index">
				<image :src="item" mode="aspectFill" class="slide-image"></image>
			</swiper-item>
		</swiper>
		
		<!-- 价格区域 -->
		<view class="price-section">
			<view class="price-left">
				<view class="current-price">
					<text class="symbol">¥</text>
					<text class="price-value">{{courseInfo.price}}</text>
				</view>
				<view class="price-tag" v-if="courseInfo.price < courseInfo.originalPrice">限时特价</view>
			</view>
		</view>
		
		<!-- 课程标题区域 -->
		<view class="course-title-section">
			<view class="title-icon">
				<text class="dot"></text>
			</view>
			<view class="title-content">
				{{courseInfo.title}}
			</view>
		</view>
		
		<!-- 课程基本信息 -->
		<view class="course-intro">
			<view class="intro-text">
				{{courseInfo.description}}
			</view>
			<view class="course-info">
				<text class="update-info">已更新{{courseInfo.updatedEpisodes}}期/{{courseInfo.totalEpisodes}}期</text>
			</view>
		</view>
		
		<!-- 选项卡区域 -->
		<view class="tab-section">
			<view class="tab-item" :class="{ active: activeTab === 'intro' }" @click="switchTab('intro')">
				<text>课程介绍</text>
			</view>
			<view class="tab-item" :class="{ active: activeTab === 'location' }" @click="switchTab('location')">
				<text>授课地点</text>
			</view>
			<!-- <view class="tab-item" :class="{ active: activeTab === 'videos' }" @click="switchTab('videos')">
				<text>课程视频</text>
			</view> -->
		</view>
		
		<!-- 选项卡内容区域 -->
		<view class="tab-content">
			<!-- 课程介绍内容 -->
			<view class="tab-pane" v-if="activeTab === 'intro'">
				<view class="course-content" v-if="courseInfo.content">
					<rich-text :nodes="courseInfo.content"></rich-text>
				</view>
				<view class="empty-content" v-else>
					<image src="/static/images/empty_data.png" mode="aspectFit" class="empty-image"></image>
					<text class="empty-text">暂无课程介绍内容</text>
				</view>
			</view>
			
			<!-- 授课地点内容 -->
			<view class="tab-pane" v-if="activeTab === 'location'">
				<view class="location-detail" v-if="courseInfo.courseType === false && courseInfo.location">
					<view class="location-title">
						<text class="icon-location">📍</text>
						<text>授课地点</text>
					</view>
					<view class="location-address">{{courseInfo.location}}</view>
					<view class="location-time" v-if="courseInfo.courseTime">
						<text class="icon-time">🕒</text>
						<text>授课时间</text>
						<view class="time-detail">{{courseInfo.courseTime}}</view>
					</view>
				</view>
				<view class="online-course-notice" v-else-if="courseInfo.courseType === true">
					<image src="/static/images/online_course.png" mode="aspectFit" class="online-image"></image>
					<text class="online-text">本课程为线上课程，无需到线下地点</text>
					<view class="time-info" v-if="courseInfo.courseTime">
						<text class="time-label">开课时间：</text>
						<text class="time-value">{{courseInfo.courseTime}}</text>
					</view>
				</view>
				<view class="empty-content" v-else>
					<image src="/static/images/empty_location.png" mode="aspectFit" class="empty-image"></image>
					<text class="empty-text">暂无地点信息</text>
				</view>
			</view>
			
			<!-- 课程视频内容 -->
			<view class="tab-pane" v-if="activeTab === 'videos'">
				<view class="video-player" v-if="currentVideo">
					<video 
						:src="currentVideo.videoUrl"
						:poster="currentVideo.coverImage"
						controls
						autoplay
						class="video-player-main"
					></video>
					<view class="video-title">
						{{ currentVideo.episodeNumber }}. {{ currentVideo.title }}
					</view>
				</view>
				<!-- <view class="video-list">
					<view class="video-list-header">
						<text>课程目录</text>
						<text class="video-count">共{{ videoList.length }}个课时</text>
					</view>
					<view 
						class="video-item" 
						v-for="(item, index) in videoList" 
						:key="index"
						:class="{ active: currentVideo && currentVideo.id === item.id }"
						@click="playVideo(item)"
					>
						<view class="video-item-left">
							<text class="video-num">{{ item.episodeNumber }}</text>
							<text class="video-item-title">{{ item.title }}</text>
						</view>
						<view class="video-item-right">
							<text class="video-duration">{{ item.durationFormat }}</text>
							<text v-if="item.freePreview" class="video-free">免费</text>
							<text v-else-if="hasPaid" class="video-play">播放</text>
							<text v-else class="video-lock">付费</text>
						</view>
					</view>
					<view class="empty-content" v-if="videoList.length === 0">
						<image src="/static/images/empty_data.png" mode="aspectFit" class="empty-image"></image>
						<text class="empty-text">暂无课程视频</text>
					</view>
				</view> -->
			</view>
		</view>
		
		<!-- 底部购买栏 -->
		<view class="bottom-action">
			<view class="action-right" @click="hasPaid ? goToAppointment() : goBuy()">
				<text>{{ !isLogin ? '登录购买' : (hasPaid ? '预约参加' : '立即抢购') }}</text>
			</view>
		</view>
	</view>
</template>

<script>
	import { getCourseDetail, getProductDetail, getCourseVideos } from '@/api/store.js';
	import { preOrderApi, getOrderList } from '@/api/order.js';
	import config from '@/config/app.js';

	export default {
		data() {
			return {
				id: 0,
				orderId: 0,
				activeTab: 'intro', // 默认显示课程介绍
				hasPaid: false, // 添加这个属性，表示用户是否已购买
				courseInfo: {
					id: 0,
					title: '',
					price: '0.00',
					originalPrice: '0.00',
					banner: '',
					description: '',
					totalEpisodes: 0,
					updatedEpisodes: 0,
					courseType: true, // 默认线上课程
					location: '',
					courseTime: '',
					sliderImage: [],
					content: ''
				},
				videoList: [],
				currentVideo: null
			}
		},
		onLoad(options) {
			if (options.id) {
				this.id = options.id;
				this.getCourseDetail();
			}
		},
		methods: {
			// 切换标签页
			switchTab(tab) {
				this.activeTab = tab;
			},
			
			goBack() {
				uni.navigateBack();
			},
			
			listenSample() {
				uni.showToast({
					title: '正在加载试听内容',
					icon: 'none'
				});
			},
			
			goBuy() {
				// 检查是否有有效的课程信息
				if (!this.courseInfo || !this.courseInfo.id) {
					uni.showToast({
						title: '课程信息不完整',
						icon: 'none'
					});
					return;
				}
				
				// 检查用户是否已登录，如果未登录则跳转到登录页面
				if (!this.isLogin) {
					uni.navigateTo({
						url: '/pages/users/wechat_login/index'
					});
					return;
				}
				
				// 显示加载状态
				uni.showLoading({
					title: '处理中...'
				});
				
				// 获取最新的商品详情，确保获取到最新的规格信息
				getProductDetail(this.courseInfo.id, 'normal').then(res => {
					uni.hideLoading();
					
					if (res.data && res.data.productInfo) {
						let attrValueId = null;
						
						// 从productValue中获取规格ID
						if (res.data.productValue && Object.keys(res.data.productValue).length > 0) {
							// 获取第一个可用的规格值
							const firstKey = Object.keys(res.data.productValue)[0];
							const firstValue = res.data.productValue[firstKey];
							if (firstValue && firstValue.id) {
								attrValueId = firstValue.id;
								console.log('找到规格值ID:', attrValueId);
							}
						}
						
						// 如果没有找到规格ID，则使用商品ID
						if (!attrValueId) {
							attrValueId = this.courseInfo.id;
							console.log('使用商品ID作为规格值:', attrValueId);
						}
						
						try {
							// 使用标准的商品购买方法，但添加isCourse标记
							this.$Order.getPreOrder("buyNow", [{
								"attrValueId": parseFloat(attrValueId),
								"productId": parseFloat(this.courseInfo.id),
								"productNum": 1,
								"isCourse": true // 添加课程标记
							}]);
						} catch (error) {
							console.error('预订单创建失败:', error);
							uni.showToast({
								title: '下单失败，请重试',
								icon: 'none'
							});
						}
					} else {
						uni.showToast({
							title: '获取商品规格信息失败',
							icon: 'none'
						});
					}
				}).catch(err => {
					uni.hideLoading();
					console.error('获取商品详情失败:', err);
					uni.showToast({
						title: '下单失败，请重试',
						icon: 'none'
					});
				});
			},
			
			// 修改checkIfPaid方法，不使用$http.baseUrl
			checkIfPaid() {
				// 显示加载状态
				uni.showLoading({
					title: '加载中...'
				});
				
				const token = uni.getStorageSync('LOGIN_STATUS_TOKEN');
				console.log('当前token:', token);
				
				// 如果用户未登录，直接返回
				if (!token) {
					uni.hideLoading();
					this.hasPaid = false;
					console.log('用户未登录，默认未购买状态');
					return;
				}
				
				// 使用getOrderList API查询订单，确保传递type参数
				getOrderList({
					type: 4,  // 这是必需的参数，可能是指定订单类型
					paid: 1   // 已支付状态
				}).then(res => {
					uni.hideLoading();
					console.log('订单查询结果:', res);
					
					if (res.data && res.data.list && res.data.list.length > 0) {
						// 遍历订单列表，查找包含当前课程ID的已支付订单
						let found = false;
						
						for (let order of res.data.list) {
							// 检查订单中的商品列表是否包含当前课程
							if (order.orderInfoList && order.orderInfoList.length > 0) {
								for (let item of order.orderInfoList) {
									if (parseInt(item.productId) === parseInt(this.id)) {
										// 找到匹配的课程订单
										this.hasPaid = true;
										this.orderId = order.orderId;
										found = true;
										console.log('已购买课程，订单ID:', this.orderId);
										break;
									}
								}
							}
							
							if (found) break;
						}
						
						if (!found) {
							this.hasPaid = false;
							console.log('未找到匹配的已购买课程');
						}
					} else {
						this.hasPaid = false;
						console.log('未查询到订单');
					}
				}).catch(err => {
					uni.hideLoading();
					console.error('查询购买状态失败', err);
					this.hasPaid = false;
				});
			},
			
			// 跳转到预约页面
			goToAppointment() {
				// 检查用户是否已登录
				if (!this.isLogin) {
					uni.navigateTo({
						url: '/pages/users/wechat_login/index'
					});
					return;
				}
				
				uni.navigateTo({
					url: `/pages/course/dianhua/dianhua?courseId=${this.courseInfo.id}&orderId=${this.orderId}`
				});
			},
			
			getCourseDetail() {
				// 先显示加载状态
				uni.showLoading({
					title: '加载中...'
				});
				
				getCourseDetail(this.id).then(res => {
					uni.hideLoading();
					if (res.data) {
						console.log('课程详情数据:', res.data);
						
						// 根据数据结构获取正确的数据对象
						const productInfo = res.data.productInfo || res.data;
						
						this.courseInfo = {
							id: productInfo.id || 0,
							title: productInfo.storeName || '未命名课程',
							price: productInfo.price || '0.00',
							originalPrice: productInfo.otPrice || '0.00',
							banner: productInfo.image || '/static/images/default_course.png',
							sliderImage: productInfo.sliderImage ? productInfo.sliderImage.split(',') : [],
							description: productInfo.storeInfo || '暂无课程介绍',
							totalEpisodes: productInfo.totalEpisodes || 0,
							updatedEpisodes: productInfo.updatedEpisodes || 0,
							courseType: productInfo.courseType !== null ? productInfo.courseType : true,
							location: productInfo.location || '',
							courseTime: productInfo.courseTime || '',
							content: productInfo.content || ''
						};
						
						// 更新导航栏标题
						if (this.courseInfo.title) {
							uni.setNavigationBarTitle({
								title: this.courseInfo.title.length > 10 ? 
									   this.courseInfo.title.substring(0, 10) + '...' : 
									   this.courseInfo.title
							});
						}
						
						// 如果主图为空，尝试使用轮播图的第一张
						if (!this.courseInfo.banner && this.courseInfo.sliderImage && this.courseInfo.sliderImage.length > 0) {
							this.courseInfo.banner = this.courseInfo.sliderImage[0];
						}
						
						console.log('课程ID:', this.id);
						console.log('登录状态:', this.isLogin);
						
						// 如果是线下课程，自动切换到地点标签
						if (this.courseInfo.courseType === false && this.courseInfo.location) {
							this.activeTab = 'location';
						}
						
						// 只有在用户已登录时才检查购买状态
						if (this.isLogin) {
							this.checkIfPaid();
						}
						
						// 获取课程详情后，加载视频列表
						this.loadCourseVideos();
					}
				}).catch(err => {
					uni.hideLoading();
					console.error('获取课程详情失败', err);
					uni.showToast({
						title: '获取课程详情失败',
						icon: 'none'
					});
					
					// 只有在用户已登录时才检查支付状态
					if (this.isLogin) {
						this.checkIfPaid();
					}
				});
			},
			
			// 使用商品接口作为备用方案
			fallbackToProductDetail() {
				getProductDetail(this.id, 'normal').then(res => {
					if (res.data && res.data.productInfo) {
						const data = res.data.productInfo;
						this.courseInfo = {
							id: data.id || 0,
							title: data.storeName || '未命名课程',
							price: data.price || '0.00',
							originalPrice: data.otPrice || '0.00',
							banner: data.image || '/static/images/default_course.png',
							sliderImage: data.sliderImage ? data.sliderImage.split(',') : [],
							description: data.storeInfo || '暂无课程介绍',
							totalEpisodes: data.totalEpisodes || 0,
							updatedEpisodes: data.updatedEpisodes || 0,
							courseType: data.courseType !== null ? data.courseType : true,
							location: data.location || '',
							courseTime: data.courseTime || '',
							content: data.content || ''
						};
					}
				}).catch(err => {
					console.error('备用方案获取课程详情失败', err);
				});
			},
			
			// 获取课程视频列表
			loadCourseVideos() {
				if (!this.courseInfo.id) return;
				
				getCourseVideos(this.courseInfo.id).then(res => {
					if (res.data && res.data.length > 0) {
						this.videoList = res.data;
						
						// 如果用户已购买或有免费视频，自动播放第一个可播放的视频
						if (this.hasPaid) {
							this.currentVideo = this.videoList[0];
						} else {
							// 找到第一个免费视频
							const freeVideo = this.videoList.find(v => v.freePreview);
							if (freeVideo) {
								this.currentVideo = freeVideo;
							}
						}
					}
				}).catch(err => {
					console.error('获取课程视频列表失败', err);
				});
			},
			
			// 播放视频
			playVideo(video) {
				// 如果未购买且视频非免费，提示购买
				if (!this.hasPaid && !video.freePreview) {
					uni.showToast({
						title: '请先购买课程',
						icon: 'none'
					});
					return;
				}
				
				this.currentVideo = video;
			}
		},
		computed: {
			isLogin() {
				// 原代码：return !!uni.getStorageSync('token');
				// 修改为：
				return !!uni.getStorageSync('LOGIN_STATUS_TOKEN');
			}
		}
	}
</script>

<style lang="scss">
	.course-detail-container {
		background-color: #f8f8f8;
		min-height: 100vh;
		position: relative;
		padding-bottom: 120rpx; /* 为底部操作栏留出空间 */
	}
	
	.nav-bar {
		display: flex;
		align-items: center;
		height: 88rpx;
		padding: 0 30rpx;
		background-color: #ffffff;
		position: relative;
		
		.nav-left {
			font-size: 40rpx;
			color: #333;
		}
		
		.nav-title {
			flex: 1;
			font-size: 32rpx;
			color: #333;
			text-align: center;
			white-space: nowrap;
			overflow: hidden;
			text-overflow: ellipsis;
			margin: 0 60rpx;
		}
		
		.nav-right {
			display: flex;
			font-size: 36rpx;
			color: #333;
			
			.ml-20 {
				margin-left: 40rpx;
			}
		}
	}
	
	.banner-image {
		position: relative;
		width: 100%;
		height: 400rpx;
		
		image {
			width: 100%;
			height: 100%;
			display: block;
		}
	}
	
	.banner-swiper {
		width: 100%;
		height: 400rpx;
	}
	
	.slide-image {
		width: 100%;
		height: 100%;
	}
	
	.price-section {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx 30rpx;
		background-color: #f44336;
		color: #fff;
		
		.price-left {
			display: flex;
			align-items: center;
			
			.current-price {
				display: flex;
				align-items: baseline;
				font-weight: bold;
				
				.symbol {
					font-size: 28rpx;
				}
				
				.price-value {
					font-size: 46rpx;
				}
			}
			
			.price-tag {
				font-size: 22rpx;
				background-color: rgba(255, 255, 255, 0.2);
				padding: 4rpx 12rpx;
				border-radius: 4rpx;
				margin-left: 16rpx;
			}
		}
	}
	
	.course-title-section {
		display: flex;
		padding: 30rpx;
		background-color: #fff;
		
		.title-icon {
			display: flex;
			align-items: flex-start;
			margin-right: 10rpx;
			padding-top: 12rpx;
			
			.dot {
				width: 16rpx;
				height: 16rpx;
				background-color: #333;
				border-radius: 50%;
			}
		}
		
		.title-content {
			flex: 1;
			font-size: 30rpx;
			font-weight: bold;
			color: #333;
			line-height: 1.5;
		}
	}
	
	.course-intro {
		padding: 20rpx 30rpx 30rpx;
		background-color: #fff;
		
		.intro-text {
			font-size: 28rpx;
			color: #666;
			line-height: 1.6;
		}
		
		.course-info {
			margin-top: 20rpx;
			display: flex;
			justify-content: flex-end;
			
			.update-info {
				font-size: 24rpx;
				color: #999;
			}
		}
	}
	
	.tab-section {
		display: flex;
		height: 100rpx;
		margin-top: 20rpx;
		border-bottom: 1px solid #eee;
		background-color: #fff;
		
		.tab-item {
			flex: 1;
			display: flex;
			justify-content: center;
			align-items: center;
			font-size: 28rpx;
			color: #666;
			border-right: 1px dashed #f44336;
			position: relative; /* 添加这个 */
			
			&:last-child {
				border-right: none;
			}
			
			&.active {
				color: #f44336;
				font-weight: bold;
				
				&::after {
					content: '';
					position: absolute;
					bottom: 0;
					left: 50%;
					transform: translateX(-50%);
					width: 60rpx;
					height: 4rpx;
					background-color: #f44336;
					border-radius: 2rpx;
				}
			}
		}
	}
	
	.tab-content {
		background-color: #fff;
		min-height: 300rpx;
		
		.tab-pane {
			padding: 30rpx;
		}
		
		.course-content {
			font-size: 28rpx;
			line-height: 1.8;
			color: #666;
		}
		
		.empty-content {
			display: flex;
			flex-direction: column;
			align-items: center;
			padding: 50rpx 0;
			
			.empty-image {
				width: 200rpx;
				height: 200rpx;
				margin-bottom: 20rpx;
			}
			
			.empty-text {
				font-size: 28rpx;
				color: #999;
			}
		}
		
		.location-detail {
			padding: 20rpx;
			background-color: #f9f9f9;
			border-radius: 12rpx;
			
			.location-title {
				font-size: 30rpx;
				font-weight: bold;
				margin-bottom: 16rpx;
				display: flex;
				align-items: center;
				
				.icon-location {
					margin-right: 10rpx;
				}
			}
			
			.location-address {
				font-size: 28rpx;
				color: #333;
				line-height: 1.5;
				padding: 10rpx 0 20rpx 30rpx;
				border-bottom: 1px dashed #eee;
			}
			
			.location-time {
				margin-top: 20rpx;
				font-size: 30rpx;
				font-weight: bold;
				display: flex;
				align-items: center;
				
				.icon-time {
					margin-right: 10rpx;
				}
				
				.time-detail {
					margin-top: 10rpx;
					font-size: 28rpx;
					color: #333;
					font-weight: normal;
					padding-left: 30rpx;
				}
			}
		}
		
		.online-course-notice {
			display: flex;
			flex-direction: column;
			align-items: center;
			padding: 40rpx 0;
			
			.online-image {
				width: 200rpx;
				height: 200rpx;
				margin-bottom: 20rpx;
			}
			
			.online-text {
				font-size: 30rpx;
				color: #333;
				margin-bottom: 20rpx;
			}
			
			.time-info {
				margin-top: 20rpx;
				display: flex;
				align-items: center;
				
				.time-label {
					font-size: 28rpx;
					color: #666;
				}
				
				.time-value {
					font-size: 28rpx;
					color: #f44336;
				}
			}
		}
		
		.video-player {
			background-color: #000;
			border-radius: 12rpx;
			overflow: hidden;
			margin-bottom: 20rpx;
		}
		
		.video-player-main {
			width: 100%;
			height: 420rpx;
		}
		
		.video-title {
			padding: 20rpx;
			font-size: 28rpx;
			font-weight: bold;
			color: #333;
			background-color: #fff;
		}
		
		.video-list {
			background-color: #fff;
			border-radius: 12rpx;
			padding-bottom: 20rpx;
		}
		
		.video-list-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 20rpx;
			border-bottom: 1px solid #f0f0f0;
			font-size: 30rpx;
			font-weight: bold;
			color: #333;
		}
		
		.video-count {
			font-size: 24rpx;
			color: #999;
			font-weight: normal;
		}
		
		.video-item {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 20rpx;
			border-bottom: 1px solid #f5f5f5;
		}
		
		.video-item.active {
			background-color: #f9f9f9;
		}
		
		.video-item-left {
			display: flex;
			align-items: center;
			flex: 1;
			overflow: hidden;
		}
		
		.video-num {
			width: 50rpx;
			font-size: 28rpx;
			color: #999;
			margin-right: 10rpx;
		}
		
		.video-item-title {
			font-size: 28rpx;
			color: #333;
			white-space: nowrap;
			overflow: hidden;
			text-overflow: ellipsis;
			flex: 1;
		}
		
		.video-item-right {
			display: flex;
			align-items: center;
		}
		
		.video-duration {
			font-size: 24rpx;
			color: #999;
			margin-right: 20rpx;
		}
		
		.video-free {
			font-size: 24rpx;
			color: #07c160;
			background-color: rgba(7, 193, 96, 0.1);
			padding: 4rpx 10rpx;
			border-radius: 4rpx;
		}
		
		.video-play {
			font-size: 24rpx;
			color: #f44336;
		}
		
		.video-lock {
			font-size: 24rpx;
			color: #999;
		}
	}
	
	.bottom-action {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		display: flex;
		height: 100rpx;
		background-color: #fff;
		border-top: 1px solid #eee;
		
		.action-right {
			flex: 1;
			display: flex;
			justify-content: center;
			align-items: center;
			background-color: #f44336;
			color: #fff;
			font-size: 32rpx;
			font-weight: bold;
		}
	}
</style>
